package com.mdl.sponsorme.bbdd;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.mdl.sponsorme.modelo.ListaPubli;
import com.mdl.sponsorme.modelo.Publi;
import com.mdl.sponsorme.modelo.Propietario;

public class Publi_bbdd {
	
	private static String Publicacion 	= "Publicacion";
	private static String Propietario 	= "Propietario";
	private static String Titulo		= "Titulo";
 	
	private DatastoreService datastore = null;
	private Query query = null;
	
	public Publi_bbdd(){
		datastore = DatastoreServiceFactory.getDatastoreService();
		query = new Query(Publicacion);
	}
	
	public Key crearPublicacion(Publi publi){
		Entity entPublicacion = new Entity(Publicacion);

		entPublicacion.setProperty(Propietario, publi.getPropietarioId());
		entPublicacion.setProperty(Titulo, publi.getTitulo());
			
		return datastore.put(entPublicacion);
	}
	
	public ListaPubli getListaPubli(Propietario propietario){
		ListaPubli listaPubli = new ListaPubli();

		query.setFilter(new FilterPredicate(Propietario,FilterOperator.EQUAL,propietario.getId()));
		
		// PreparedQuery contains the methods for fetching query results
		// from the datastore
		PreparedQuery pq = datastore.prepare(query);

		for (Entity result : pq.asIterable()) {
		   Publi publi = new Publi(propietario,
				   				   (String) result.getProperty(Titulo));
		   listaPubli.add(publi);
		}
		return listaPubli;
	}
}
